package com.shiguiwu.springmybatis.mybatis;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @description: 枚举类处理mybatis
 * @author: stone
 * @date: Created by 2021/6/30 17:22
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springmybatis.mybatis
 */
@Slf4j
public class SexTypeHandle extends BaseTypeHandler<SexTypeHandle.Sex> {


    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Sex parameter, JdbcType jdbcType) throws SQLException {
        ps.setInt(i, parameter.getCode());
        log.error("设置的值为===============>{}", parameter);
    }

    @Override
    public Sex getNullableResult(ResultSet rs, String columnName) throws SQLException {
        Object object = rs.getObject(columnName);
        Integer code = object instanceof Integer ? (Integer) object : null;
        return Sex.sex(code);
    }

    @Override
    public Sex getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        log.error("{}", columnIndex);
        Object object = rs.getObject(columnIndex);
        Integer code = object instanceof Integer ? (Integer) object : null;
        return Sex.sex(code);
    }

    @Override
    public Sex getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        log.error("{}", columnIndex);
        Object object = cs.getObject(columnIndex);
        Integer code = object instanceof Integer ? (Integer) object : null;
        return Sex.sex(code);
    }

    public static enum Sex {
        UNKNOW(0, "未知"),
        MAN(1, "男"),
        WOMAN(2, "女");
        @Getter
        private Integer code;
        @Getter
        private String name;

        Sex(Integer code, String name) {
            this.code = code;
            this.name = name;
        }

        public static Sex sex(Integer code) {
            for (int i = 0; i < values().length; i++) {
                if (code.equals(values()[i].code)) {
                    return values()[i];
                }
            }
            return null;
        }

        


    }
}
